﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using Crawler.Model;
using Crawler.BusinessActions;
using System.Collections.Specialized;
using Husb.Framework;
using System.Linq.Expressions;

namespace WinFromsClient
{
    public partial class Form1 : Form
    {
        StringCollection sc = new StringCollection();
        public Form1()
        {
            InitializeComponent();


            taskBindingSource.DataSource = Task.FindAll();

        }

        string a = @"
					<h2>
						<a id=""ArchiveMonth1_Days_Entries_ctl01_TitleUrl"" href=""http://www.cnblogs.com/sunway/archive/2010/01/20/1652609.html"">C# 中的泛型</a>
					";

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //WebPageInfo webPage = GetNavigationPageContent("http://www.cnblogs.com");

            WebPage webPage = new WebPage();
            //List<WebPageInfo> pages = webPage.GetNavigationPageContent("http://www.cnblogs.com");
            //List<WebPageInfo> pages = webPage.GetNavigationPageHtml("http://www.cnblogs.com", "<div class=\"post_item_body\">", "</h3>");
            //List<WebPageInfo> pages = webPage.GetNavigationPageHtml("http://www.cnblogs.com",
            //    "<div class=\"post_item_body\">",
            //    "</h3>",
            //    @"<div class[\s]*=[\s]*""post""[\s]*[^>]*>",
            //    @"<div id=""post_next_prev"">");

            List<WebPageInfo> pages = webPage.GetNavigationPageHtml("http://www.cnblogs.com/sunway/archive/2010/01.html",
                "<div class=\"posthead\">",
                "</h2>",
                @"<div class[\s]*=[\s]*""post""[\s]*>",
                @"<div id=""post_next_prev"">");

            //List<WebPageInfo> pages = webPage.GetNavigationPageHtml("http://www.cnblogs.com/JeffreyZhao/",
            //    @"<div class[\s]*=[\s]*""post""[\s]*[^>]*",
            //    "</h2>",
            //    @"<div class[\s]*=[\s]*""post""[\s]*[^>]*>",
            //    @"<div id=""post_next_prev"">");

            // (?<=<div class[\s]*=[\s]*"post"[\s]*[^>]*>)[\s\S]*?(?=</h2>)

            // @"(?<=<div class[\s]*=[\s]*""post""[\s]*>)[\s\S]*?(?=<div id=""post_next_prev"">)";

            if (pages.Count > 0)
            {
                textBox1.Text = pages[0].ContentText;
                webBrowser1.DocumentText = textBox1.Text;
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            lv.Items.Clear();

            WebPage webPage = new WebPage();
            BindingListView<WebPageInfo> pages = new BindingListView<WebPageInfo>(  WebPage.FindAll());

            foreach (WebPageInfo page in pages)
            {
                ListViewItem line = new ListViewItem();
                
                line.SubItems.Clear();
                line.SubItems[0].Text = page.Id.ToString();
                line.SubItems.Add(page.Name);
                line.SubItems.Add(page.Url);
                line.SubItems.Add(page.CreatedDate.ToString());
                
                
                lv.Items.Add(line);
            }
        }

        private void lv_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListView.SelectedIndexCollection selecteds = lv.SelectedIndices;
            ListView.SelectedListViewItemCollection items = lv.SelectedItems;
            if (items.Count > 0)
            {
                ListViewItem current = items[0];
                string id = current.SubItems[0].Text;

                WebPageInfo page = WebPage.GetById(new Guid(id));

                //webBrowser1.DocumentText = page.ContentText;

                //textBox1.Text = page.ContentText;

                //string imgPattern = @"(?<=<img [\s\S]*?src[\s]*=[\s]*""?)[\s\S]+?(?=[ ]+)";
                //MatchCollection matches = GetMatches(imgPattern, page.ContentText);

                //foreach (Match match in matches)
                //{
                //    string s = match.Value;
                //}

                //using (FileStream fs = File.Open("aa.zip", FileMode.Create, FileAccess.ReadWrite))
                //{
                //    using (MemoryStream ms = new MemoryStream(Crawler.BusinessActions.WebPage.CompressHtml(page.ContentText, page.Url)))
                //    {
                //        int readCount;
                //        byte[] buffer = new byte[1024];

                //        while ((readCount = ms.Read(buffer, 0, buffer.Length)) != 0)
                //        {
                //            fs.Write(buffer, 0, readCount);
                //        }
                //    }
                //}

                string path = Path.GetTempPath() + "Tips\\" + page.Id.ToString("N") + "\\";
                if (sc.Contains(page.Id.ToString("N")) && Directory.Exists(path))
                {
                    webBrowser1.Navigate("file:///" + path.Replace('\\', '/') + "ArticleContent.htm");
                }
                else
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    bool hasArticle = WebPage.GetArticleContent(page.Id, path);
                    if (hasArticle)
                    {
                        webBrowser1.Navigate("file:///" + path.Replace('\\', '/') + "ArticleContent.htm");
                    }
                    sc.Add(page.Id.ToString("N"));
                }
            }
        }

        private static MatchCollection GetMatches(string pattern, string originalText)
        {
            Regex tmpRegex = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection matches = tmpRegex.Matches(originalText);

            return matches;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            string path = Path.GetTempPath() + "Tips\\";
            if (Directory.Exists(path))
            {
                Directory.Delete(Path.GetTempPath() + "Tips\\", true);
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            string s = Crawler.BusinessActions.Utilities.FixUpUrl("blog.csdn.net/kissjob/archive/2009/12/03/4931321.aspx", "Http://images/abc.png");
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            TaskInfo task = new TaskInfo();
            task.Id = Guid.NewGuid();

            TaskForm form = new TaskForm( task, Husb.Util.DataViewMode.Insert);
            form.ShowDialog();
        }

        private void editTaskMenuItem_Click(object sender, EventArgs e)
        {
            TaskInfo task = taskBindingSource.Current as TaskInfo;
            if (task != null)
            {
                task.TaskItems = new BindingListView<TaskItemInfo>( TaskItem.GetByMasterId(task.Id));
                foreach (TaskItemInfo item in task.TaskItems)
                {
                    item.Task = task;
                }

                TaskForm form = new TaskForm(task, Husb.Util.DataViewMode.Edit);
                form.ShowDialog();
            }
        }

        private void executeMenuItem_Click(object sender, EventArgs e)
        {
            TaskInfo task = taskBindingSource.Current as TaskInfo;
            if (task != null)
            {
                task.TaskItems = new BindingListView<TaskItemInfo> (  TaskItem.GetByMasterId(task.Id));
                WebPage webPage = new WebPage();
                foreach (TaskItemInfo taskItem in task.TaskItems)
                {
                    //taskItem.CaptureRules = CaptureRule.GetByMasterId(taskItem.Id);
                    //if (taskItem.IsNavigation != null && taskItem.IsNavigation.Value)
                    //{
                    //    CaptureRuleInfo ruleNavigation = taskItem.CaptureRules.FirstOrDefault(r => r.Category == 0);
                    //    if (ruleNavigation != null)
                    //    {
                    //        CaptureRuleInfo ruleContent = taskItem.CaptureRules.FirstOrDefault(r => r.Category == 1);

                    //        WebPage webPage = new WebPage();
                    //        List<WebPageInfo> pages = webPage.GetNavigationPageHtml(taskItem.Url,
                    //            ruleNavigation.StartString,
                    //            ruleNavigation.EndString,
                    //            ruleContent.StartString,
                    //            ruleContent.EndString);
                    //    }
                    //}
                    //else
                    //{
                    //    CaptureRuleInfo rule = taskItem.CaptureRules.FirstOrDefault(r => r.Category == 1);
                    //    if (rule != null)
                    //    {
                    //        WebPage.InsertSinglePage(taskItem.Url, rule.StartString, rule.EndString);
                    //    }
                    //}

                    webPage.GetNavigationPageHtml(taskItem);
                }
            }
        }

        private void addMenuItem_Click(object sender, EventArgs e)
        {
            TestMethod(5);

            // Prove that del2 still has a copy of
            // local variable j from TestMethod.
            bool result = del2(10);

            // Output: True
            //Console.WriteLine(result);
            MessageBox.Show(result.ToString());

            Expression<Func<int, int>> exp1 = a => -a;
            Expression<Func<int, int>> exp2 = a => -a;
            Expression<Func<double, double, double, double, double>> myExp = (a, b, m, n) => m * a * a + n * b * b;




            TaskInfo task = new TaskInfo();
            task.Id = Guid.NewGuid();

            TaskForm form = new TaskForm(task, Husb.Util.DataViewMode.Insert);
            form.ShowDialog();
        }

        private void tbDelete_Click(object sender, EventArgs e)
        {
            ListView.SelectedIndexCollection selecteds = lv.SelectedIndices;
            ListView.SelectedListViewItemCollection items = lv.SelectedItems;

            if (items.Count > 0)
            {
                ListViewItem current = items[0];
                string id = current.SubItems[0].Text;

                WebPage.Delete(new Guid(id));

                lv.Items.Remove(current);
            }
        }
        //http://go.microsoft.com/fwlink/?LinkId=108181


        delegate bool D();
        delegate bool D2(int i);

        D del;
        D2 del2;
        public void TestMethod(int input)
        {
            int j = 0;
            // Initialize the delegates with lambda expressions.
            // Note access to 2 outer variables.
            // del will be invoked within this method.
            del = () => { j = 10; return j > input; };

            // del2 will be invoked after TestMethod goes out of scope.
            del2 = (x) => { return x == j; };

            // Demonstrate value of j:
            // Output: j = 0 
            // The delegate has not been invoked yet.
            //Console.WriteLine("j = {0}", j);
            MessageBox.Show(String.Format("j = {0}", j));

            // Invoke the delegate.
            bool boolResult = del();

            // Output: j = 10 b = True
            //Console.WriteLine("j = {0}. b = {1}", j, boolResult);
            MessageBox.Show(String.Format("j = {0}. b = {1}", j, boolResult));
        }

    }
}
